/**
 * 
 */
package com.base.myproject.client.busi.service.analysis;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.tools.CalendarUtils;
import com.base.myproject.client.tools.Debug;
import com.base.myproject.client.tools.SendServlet;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridGroupRenderer;
import com.extjs.gxt.ui.client.widget.grid.GroupColumnData;
import com.extjs.gxt.ui.client.widget.grid.GroupSummaryView;
import com.extjs.gxt.ui.client.widget.grid.SummaryColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.SummaryType;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

/**
 * 会员充值和消费查询，条件：时间段，店面
 * 
 * @author zgw 2009-12-6 下午07:59:49 javazgw@gmail.com
 */
public class FinaceAndSaleAnalysis extends ContentPanel {
	GroupingStore<BusiObject> store;
	BaseComboBoxForm<BaseModelData> systemid_t;
	DateField qdatefrom = new DateField();
	DateField qdateto = new DateField();
	// final DatePicker picker = new DatePicker();
	DateTimeFormat activeFormat = DateTimeFormat.getFormat("yyyy-M-d");

	BasePagingLoader<PagingLoadResult<BusiObject>> loder;
	SendServlet ss = new SendServlet();
	ModelType type;
	StoreInfo info;
	Grid grid;
	ColumnModel cm;
	CheckBox s_service_po_check = new CheckBox();
	CheckBox s_service_finance_check= new CheckBox();
	

	public FinaceAndSaleAnalysis() {
		init();
	}

	void init() {
		Date d = new Date();
		d = CalendarUtils.addDays(d,1);
		qdatefrom.setValue(new Date());
		qdateto.setValue(d);
		s_service_po_check.setValue(true);
		s_service_finance_check.setValue(true);
		setWidth("760px");
		setHeading("综合查询");
		// initstore();
		initstore();
		initWidget();
	}

	void initstore() {
		type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");

		type.addField("systemname");
		type.addField("bname");
		type.addField("cname");
		type.addField("s_cardno");
		
		type.addField("finance");
		type.addField("finance_real");
		type.addField("finance_gif");
		type.addField("type");
		type.addField("updatedate");
		//type.getField("finance").setType(Double.class);
		info = new StoreInfo();

		info.setTablename("aa");
		info.setNeedAllRow("no");

		info.setSql(initreloadparam());
		loder = ss.getBaseLoaderX(type, info);
		store = new GroupingStore<BusiObject>(loder);
		loder.load();
		store.groupBy("systemname");
	}

	void initWidget() {

		VerticalPanel vpanel = new VerticalPanel();

		vpanel.add(new Html("<br>"));
		vpanel.add(initQuery());
		vpanel.add(new Html("<br>"));
		// vpanel.add(CreateGrid());
		vpanel.add(CreateGrid());

		add(vpanel);

	}

	Widget CreateGrid() {
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		//columns.add(cbs.getColumn());
		columns.add(new SummaryColumnConfig("systemname", "店名", 80));
		columns.add(new SummaryColumnConfig("bname", "充值人", 80));
		columns.add(new SummaryColumnConfig("cname", "会员", 80));
		columns.add(new SummaryColumnConfig("s_cardno", "卡号", 80));
		
		//columns.add(new SummaryColumnConfig("finance", "金额", 100));
		columns.add(new SummaryColumnConfig("type", "类型", 100));

		columns.add(new SummaryColumnConfig("updatedate", "发生日期", 100));

		SummaryColumnConfig<Double> project = new SummaryColumnConfig<Double>("finance", "总金额", 100); 
		project.setNumberFormat(NumberFormat.getCurrencyFormat());  
		project.setSummaryFormat(NumberFormat.getCurrencyFormat());  
		project.setSummaryType(SummaryType.SUM);  
		project.setAlignment(HorizontalAlignment.RIGHT);  
		
		columns.add(project);  
		
		SummaryColumnConfig<Double> finance_real = new SummaryColumnConfig("finance_real", "充值金额", 100);
		finance_real.setSummaryType(SummaryType.SUM);  
		columns.add(finance_real);
		
		
		SummaryColumnConfig<Double> finance_gif =new SummaryColumnConfig("finance_gif", "赠送金额", 100);
		finance_gif.setSummaryType(SummaryType.SUM);  
		columns.add(finance_gif);
		
		 cm = new ColumnModel(columns);
		// cm.addAggregationRow(averages);
		//cbs.setSelectionMode(SelectionMode.SINGLE);

		GroupSummaryView view = new GroupSummaryView();
		//view.setShowGroupedColumn(false);
		view.setShowDirtyCells(false);
		view.setForceFit(true);
		view.setGroupRenderer(new GridGroupRenderer() {
			public String render(GroupColumnData data) {
				String f = cm.getColumnById(data.field).getHeader();
				String l = data.models.size() == 1 ? "条" : "条";
				return f + ": " + data.group + " (" + data.models.size() + " "
						+ l + ")";
			}
		});
		view.setShowGroupedColumn(false);
		grid = new Grid(store, cm);
	//	grid.setSelectionModel(cbs);
		grid.setView(view);
		grid.setLoadMask(true);
		grid.setSize(760, 400);
		return grid;
	}

	Widget initQuery() {
		HorizontalPanel hpanel = new HorizontalPanel();
		FormPanel fp = new FormPanel();
		fp.setHeaderVisible(false);
		TableLayout tl = new TableLayout(6);
		fp.setLayout(tl);
		TableData td = new TableData();
		
		
	//	hpanel.add(new Label("日期："));

		qdatefrom.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-M-d"));
		qdatefrom.setFieldLabel("起始时间：");
		qdateto.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-M-d"));
		qdateto.setFieldLabel("终止时间：");
		qdatefrom.setAllowBlank(false);
		qdateto.setAllowBlank(false);
		systemid_t = com.base.myproject.client.ui.codenamemap.CodeNameMapFactory
				.createSysteminfoInput_F();
		systemid_t.validate(false);
		systemid_t.setToolTip("空表示查询全部");
		systemid_t.setFieldLabel("店名：");
		fp.add(new Label("起始时间："),td);
		fp.add(qdatefrom,td);
		fp.add(new Label("终止时间："),td);
		fp.add(qdateto,td);
		fp.add(new Label("店名："),td);
		fp.add(systemid_t,td);
		s_service_po_check.setFieldLabel("只显示消费");
		fp.add(new Label("显示消费："),td);
		fp.add(s_service_po_check,td);
		s_service_finance_check.setFieldLabel("只显示充值");
		fp.add(new Label("显示充值："),td);
		fp.add(s_service_finance_check,td);
		
		Button query = new Button("查询");
		fp.add(query,td);
		
		Button groupby1 = new Button("分别显示充值和消费");
		fp.add(groupby1,td);
		groupby1.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				if(ce.getButton().getText().equals("分别显示充值和消费"))
				{
				store.groupBy("type");
				ce.getButton().setText("根据店名分别显示");
				}
				else if(ce.getButton().getText().equals("根据店名分别显示"))
				{
					store.groupBy("systemname");
					ce.getButton().setText("分别显示充值和消费");
				}
			}
			
		});
		query.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				if (qdatefrom.isValid()
						&& qdateto.isValid()
						&& (systemid_t.isValid() || systemid_t.getValue() == null)) {
					
					info.setSql(initreloadparam());
				
					String groupfield = store.getGroupState();
					store.removeAll();
					loder = null;
					loder = ss.getBaseLoaderX(type, info);
					store = new GroupingStore<BusiObject>(loder);
					store.groupBy(groupfield);
					grid.reconfigure(store,cm);
					loder.load();
				} else {
					MessageBox.alert("警告", "请录入查询条件。店名不录可以查询所有店面的信息", null);
				}
			}

		});

		hpanel.add(fp);
		return hpanel;
	}

	String initreloadparam() {

		String sql = "";// =
						// "select * from s_service_finance where datediff(day,updatedate,'"+activeFormat.format(qdate.getValue())+"')=0";

		sql += " select * from";
		sql += " (   ";
		
		if(!s_service_po_check.getValue()  && !s_service_finance_check.getValue())
			sql+="select null as finance ,null as ccode,null as bcode,null  as updatedate,null as type  ";
		if(s_service_po_check!=null && s_service_po_check.getValue())
		{
		sql += " select paid*-1 as finance ,ccode,bcode,serviceenddate as updatedate,'消费' as type,null as finance_real,null as finance_gif from s_service_po  where busistatus=524288 and serviceenddate between '"
				+ activeFormat.format(qdatefrom.getValue())
				+ "' and '"
				+ activeFormat.format(qdateto.getValue()) + "'";
		
		}
		if(s_service_po_check!=null && s_service_po_check.getValue() &&s_service_finance_check!=null && s_service_finance_check.getValue())
		{
		sql += " union all   ";
		}
		if(s_service_finance_check!=null && s_service_finance_check.getValue())
		{
		sql += " select isnull(finance*dc,0) as finance,ccode,bcode,updatedate,'充值'  as type,finance_real,finance_gif  from  s_service_finance where updatedate between '"
				+ activeFormat.format(qdatefrom.getValue())
				+ "' and '"
				+ activeFormat.format(qdateto.getValue()) + "'    ";
		}
		sql += " ) as a                   ";
		sql += "                                         ";
		sql += " left join    ";
		sql += " (    ";
		sql += " select cname,ccode,s_cardno from ccode";
		sql += " )";
		sql += " as b  ";
		sql += " on  a.ccode = b.ccode";
		sql += "   ";
		sql += " left join";
		sql += " ( ";
		sql += " select bname,(select name from systeminfo where bcode.systemid = systeminfo.id) as systemname,bcode from bcode ";
		sql += " ) as c   ";
		sql += " on a.bcode = c.bcode";

		
		 if(!(systemid_t==null || systemid_t.getValue()==null))
		 {
		 sql += " where systemname = '"+systemid_t.getValue().get("name")+"' ";
		 }
		 sql += " order by updatedate desc";
		//sql = URL.encode(sql);
		Debug.printf("sql=" + sql);
		return sql;
	}
}
